package com.neu.controller;


import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageInfo;
import com.neu.common.Result;
import com.neu.dao.HotelDao;
import com.neu.entity.Book;
import com.neu.entity.Hotel;
import com.neu.entity.Params;
import com.neu.entity.Reserve;
import com.neu.service.BookService;
import com.neu.service.HotelService;
import com.neu.service.ReserveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/reserve")
public class ReserveController {
    @Autowired
    private ReserveService reserveService;
//    @Autowired
//    private HotelService hotelService;
    @Autowired
    private HotelDao hotelDao;

    @GetMapping("/search")
    public Result findBySearch(Params params){
        PageInfo<Reserve> info = reserveService.findBySearch(params);
        return Result.success(info);
    }

    @PostMapping
    public Result add(@RequestBody Reserve reserve){
//        if(reserve.getId() == null){
//            reserveService.add(reserve);
//        }else{
//            reserveService.update(reserve);
//        }
        //TODO
        //1.酒店剩余房间是否为0，大于0的时候才可以被预定
        Hotel hotel = hotelDao.selectByPrimaryKey(reserve.getHotelId());
        if(hotel.getNum() == 0){
            return Result.error("酒店该房间已预订完，请预订其他房间");
        }

        //2.往预订表里插入一条预订记录
        reserve.setTime(DateUtil.now());
        reserveService.add(reserve);
        //3.对应的酒店房间剩余数量减一
        hotel.setNum(hotel.getNum()-1);
        hotelDao.updateByPrimaryKeySelective(hotel);

        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        reserveService.delete(id);
        return Result.success();
    }
}
